package com.example.parallelandroid;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.parallelandroid.entity.User;
import com.example.parallelandroid.entity.UserInfo;
import com.google.gson.Gson;
import com.next.easynavigation.view.EasyNavigationBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import cn.smssdk.gui.util.Const;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainFromActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView textView_main;
    private ImageView mDrawerLayout;
    private EasyNavigationBar navigationBar;
    private List<Fragment> fragmentList = new ArrayList<>();
    private String[] tabText = {"角色","学习", "排行", "解锁"};
    private boolean flag = true;
    private Handler mHandler = new Handler();
    private SharedPreferences sharedPreferences;
    private String UID;
    //未选中icon
    private int[] normalIcon = {R.mipmap.me,R.mipmap.index,  R.mipmap.message, R.mipmap.find};
    //选中时icon
    private int[] selectIcon = {R.mipmap.me1,R.mipmap.index1,  R.mipmap.message1,R.mipmap.find1,};
    private EasyNavigationBar easyBars;
    //private List<android.support.v4.app.Fragment> fragments = new ArrayList<>();

    //提醒的dialog
    private MyDialog myDialog;
    //熬夜提醒相关全局变量
    private SharedPreferences clock;
    private boolean late;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_from);
        //获取全局变量
        clock = getSharedPreferences("Clock",MODE_PRIVATE);
        late = clock.getBoolean("lateSwitch",false);
        if (late){
            GregorianCalendar latecalendar = new GregorianCalendar();
            int latehour = latecalendar.get(Calendar.HOUR_OF_DAY);
            if(latehour>=0) {
                myDialog=new MyDialog(MainFromActivity.this,R.style.MyDialog);
                myDialog.setTitle("熬夜提醒");
                myDialog.setMessage("      夜深了，该睡觉了" +
                        "\n请您合理安排作息时间喔~");
                myDialog.setYesOnclickListener("确定", new MyDialog.onYesOnclickListener() {
                    @Override
                    public void onYesOnclick() {
                        Toast.makeText(getApplicationContext(),"晚安",Toast.LENGTH_LONG).show();
                        myDialog.dismiss();
                    }
                });
                myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        Toast.makeText(getApplicationContext(),"早点休息",Toast.LENGTH_LONG).show();
                        myDialog.dismiss();
                    }
                });
                myDialog.show();
            }

        }else {

        }

        // 获取控件对象
        getViews();
        sharedPreferences = getSharedPreferences("userinfo",
                MODE_PRIVATE);
        init();
    }
    //从后端读取信息并放入SP中
    private void init() {
        //从SP中获取userId
        sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
        UID = sharedPreferences.getString("userId", "");
        OkHttpClient okHttpClient = new OkHttpClient();
        Constant.logger.info("开始从服务端获取UserInfo数据 userId=" + UID);
        Request request = new Request.Builder()
                //设置请求地址，请求方式默认get
                .url(Constant.BASE_URL + "userInfo/findUserInfoByUserId?userId=" + UID)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Constant.logger.warn("从服务端获取UserInfo数据: 失败", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String s = response.body().string();
                    JSONObject jsonObject = new JSONObject(s);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                    String jsonStr = jsonObject.getString("data");
                    if(!(jsonStr == null || "".equals(jsonStr))){
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("userInfo",jsonStr);
                        editor.commit();
                    }
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }
        private void getViews() {
        /*toolbar=findViewById(R.id.main_from_toolbar);
        textView_main=findViewById(R.id.main_from_toolbar_text);*/
        //toolbar = findViewById(R.id.main_toolbar);
        easyBars = (EasyNavigationBar) findViewById(R.id.easy_bars);
        fragmentList.add(new RoleFragment());
        fragmentList.add(new StudyFragment());
        //这个位置add四个页面
        fragmentList.add(new RankingFragment());
        fragmentList.add(new UnlockFragment());
        easyBars.titleItems(tabText)//导航栏文字 Tab文字集合  只传文字则只显示文字
                .fragmentList(fragmentList)//存放fragment的集合.
                .normalIconItems(normalIcon)   //  Tab未选中图标集合
                .selectIconItems(selectIcon)   //  Tab选中图标集合
                .fragmentManager(getSupportFragmentManager())//fragment管理器
                /*.selectIconItems(selectList)//选中的图片
                .normalIconItems(unSelectList)//未选中的图片*/
                .setOnTabClickListener(new EasyNavigationBar.OnTabClickListener() {
                    @Override
                    public boolean onTabSelectEvent(View view, int position) {
                        //Tab点击事件  return true 页面不会切换
                        //Log.e("show",""+position);
                        /*if(position==0||position==2||position==3){
                            textView_main.setText(tabText[position]);
                        }
                        if(position==1){
                            //textView_main.setText(tabText[position]);
//                            Intent intent = new Intent(MainFromActivity.this,RoleActivity.class);
//                            intent.putExtra("Extra_data","UID");
//                            startActivity(intent);
                        }*/
                        return false;
                    }
                    @Override
                    public boolean onTabReSelectEvent(View view, int position) {
                        //Tab重复点击事件
                        return false;
                    }
                })
                .canScroll(false)//不可以滑动切换页面
                .mode(EasyNavigationBar.NavigationMode.MODE_NORMAL)
                .selectTextColor(Color.parseColor("#0000FF"))//选中的文字颜色
                .normalTextColor(Color.parseColor("#9D9D9D"))//未选中的文字颜色
                .setOnCenterTabClickListener(new EasyNavigationBar.OnCenterTabSelectListener() {
                    @Override
                    public boolean onCenterTabSelectEvent(View view) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                //＋ 旋转动画
                                if (flag) {
                                    navigationBar.getCustomAddView().animate().rotation(180).setDuration(400);
                                } else {
                                    navigationBar.getCustomAddView().animate().rotation(0).setDuration(400);
                                }
                                flag = !flag;
                            }
                        });
                        return false;
                    }
                })
                .build();//最后一定要记得.build

    }
    //用反射给toolbar控件里的mLogo设置点击事件


        /*try {
            Field field = toolbar.getClass().getDeclaredField("mLogoView");
            field.setAccessible(true);
            ImageView imageView = (ImageView) field.get(toolbar);
            //imageView.setTransitionName("SEIV");
            imageView.setId(R.id.tool_bar_log);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //点击头像打开侧部设置
                    Log.e("头像点击","success");
                }
            });
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }*/
    }